<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--患者数据-->
            <el-row style="border-bottom:1px solid #000">
                <el-form :model="queryParams" ref="queryForm" :rules="queryFormRules" size="small" :inline="true"
                    label-width="80px">
                    <el-form-item label="患者手机" prop="patientPhone">
                        <el-input v-model="queryParams.patientPhone" placeholder="请输入患者手机" clearable style="width: 240px"
                            maxlength="11" />
                    </el-form-item>
                    <el-form-item label="专病名称" prop="diseaseId">
                        <el-select v-model="queryParams.diseaseId" placeholder="请选择专病名称" style="width: 240px" clearable>
                            <el-option v-for="dict in dict.type.sys_manage_diseases" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="患者卡号">
                        <el-input v-model="queryParams.cardNumber" placeholder="请输入患者卡号" clearable style="width: 240px" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="refresh">刷新</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row style="margin-top:15px;border-bottom:1px solid #000">
                <el-col :span="20" :offset="2">
                    <el-form :model="baseInfo" ref="baseInfoForm" size="small" :inline="true" label-width="78px"
                        :rules="baseInfoFormRules">
                        <el-row>
                            <el-form-item label="患者卡号" prop="cardNumber">
                                <el-input v-model="baseInfo.cardNumber" placeholder="请输入患者卡号" clearable
                                    style="width: 240px" />
                            </el-form-item>
                            <el-form-item label="患者姓名" prop="patientName">
                                <el-input v-model="baseInfo.patientName" placeholder="请输入患者姓名" clearable
                                    style="width: 240px" />
                            </el-form-item>
                            <el-form-item label="患者性别" prop="sex">
                                <el-select v-model="baseInfo.sex" placeholder="请选择患者性别" style="width: 240px">
                                    <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                                        :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="出生日期">
                                <el-date-picker v-model="baseInfo.birthDate" type="date" placeholder="出生日期"
                                    style="width: 240px" value-format="yyyy-MM-dd">
                                </el-date-picker>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="患者手机" prop="patientPhone">
                                <el-input v-model="baseInfo.patientPhone" placeholder="请输入患者手机" clearable
                                    style="width: 240px" maxlength="11" />
                            </el-form-item>
                            <el-form-item label="患者地址">
                                <el-cascader v-model="baseInfo.area" placeholder="请选择患者地址" class="picker-form"
                                    :options="areaList" :props="{ children: 'childrenList', value: 'id', label: 'name' }"
                                    style="width: 240px">
                                </el-cascader>
                            </el-form-item>
                            <el-form-item label="详细地址">
                                <el-input v-model="baseInfo.address" placeholder="请输入详细地址" clearable style="width: 240px" />
                            </el-form-item>
                            <el-form-item label="患者类别" prop="category">
                                <el-select v-model="baseInfo.category" placeholder="请选择患者类别" style="width: 240px">
                                    <el-option v-for="dict in dict.type.sys_user_category" :key="dict.value"
                                        :label="dict.label" :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-row>
                    </el-form>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="4">
                    <el-row v-if="medicalRecordsList.length === 0">
                        <span>该患者无就诊信息</span>
                    </el-row>
                    <el-row v-else v-for="item in medicalRecordsList" :key="item.visitId">
                        <span style="cursor:pointer" :class="item.visitId === activeVisitId ? 'redColor' : ''"
                            @click="visitsClick(item)">{{ item.name }}</span>
                        <el-button @click="deleteDetail(item)" size="mini" style="float:right"> 删除</el-button>
                    </el-row>
                </el-col>
                <el-col :span="19" :offset="1">
                    <el-tabs v-model="activeName" type="card" @tab-click="tabHandleClick">
                        <el-tab-pane label="就诊信息" name="medicalRecords">
                            <el-row style="margin: 20px">
                                <el-form :model="visitInfo" ref="visitInfoForm" size="small" :inline="true"
                                    label-width="78px" :rules="visitInfoFormRules">
                                    <el-form-item label="就诊日期" prop="createTime">
                                        <el-date-picker v-model="visitInfo.createTime" type="datetime" placeholder="就诊日期"
                                            style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss">
                                        </el-date-picker>
                                    </el-form-item>
                                    <el-form-item label="就诊门诊" prop="deptId">
                                        <el-select v-model="visitInfo.deptId" style="width: 240px" placeholder="请选择就诊门诊">
                                            <el-option v-for="item in deptOptionsChildren" :key="item.id"
                                                :label="item.label" :value="item.id"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="专病名称" prop="diseaseId">
                                        <el-select v-model="visitInfo.diseaseId" placeholder="请选择专病名称" style="width: 240px"
                                            @change="getListClassify">
                                            <el-option v-for="dict in dict.type.sys_manage_diseases" :key="dict.value"
                                                :label="dict.label" :value="dict.value"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="专病分类" prop="diseaseClassifyId">
                                        <el-select v-model="visitInfo.diseaseClassifyId" placeholder="请选择专病分类"
                                            style="width: 240px">
                                            <el-option v-for="item in classifyList" :key="item.diseaseClassifyId"
                                                :label="item.diseaseClassifyName"
                                                :value="item.diseaseClassifyId"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="专属医生" prop="doctorId">
                                        <el-select v-model="visitInfo.doctorId" placeholder="请选择专属医生" style="width: 240px">
                                            <el-option v-for="item in doctorList" :key="item.userId" :label="item.userName"
                                                :value="item.userId"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="治疗状态" prop="status">
                                        <el-select v-model="visitInfo.status" placeholder="请选择治疗状态" style="width: 240px">
                                            <el-option v-for="dict in dict.type.sys_diagnosis_status" :key="dict.value"
                                                :label="dict.label" :value="dict.value"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="初诊复诊">
                                        <el-radio-group v-model="visitInfo.visitStatus" style="width: 240px">
                                            <el-radio v-for="item in visitStatusList" :key="item.id" :label="item.id">{{
                                                item.name }}</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                    <div style="display:flex;justify-content:center">
                                        <el-button type="primary" size="mini" @click="saveBaseInfo">
                                            新 增
                                        </el-button>
                                        <el-button type="primary" size="mini" @click="updateBaseInfo">
                                            修 改
                                        </el-button>
                                    </div>

                                </el-form>
                            </el-row>
                        </el-tab-pane>
                        <el-tab-pane label="照片" name="pic">
                            <div v-if="picData.length > 0">
                                <el-row>
                                    <el-col :span="4">
                                        <el-select v-model="picDataQueryParams.diseaseId" placeholder="请选择专病名称"
                                            style="width: 240px" clearable>
                                            <el-option v-for="dict in dict.type.sys_manage_diseases" :key="dict.value"
                                                :label="dict.label" :value="dict.value"></el-option>
                                        </el-select>
                                    </el-col>
                                    <el-col :span="3" :offset="1">
                                        <el-button type="primary" size="mini" @click="morePics">更多照片</el-button>
                                    </el-col>
                                </el-row>
                                <div style="margin:20px">
                                    <div v-for="(item, index) in picData" :key="item.photoId" style="margin-top:15px">
                                        <el-row>
                                            <span style="color:red" v-show="index === 0">最近照片 </span>
                                            拍摄时间:{{ item.createTime }} 拍摄者:{{ item.createBy }} 照片类型:{{
                                                item.photoUploadTypeName }}
                                            光照类型:{{ item.photoLightingTypeName }} AI MASA:5
                                            <el-button type="primary" size="mini"
                                                @click="deletePics(item.photoId)">删除</el-button>
                                        </el-row>
                                        <el-row style="display:flex;justify-content:space-around">
                                            <el-image style="width: 200px; height: 200px;margin:15px"
                                                :src="baseUrl + item.leftPhotoAddress" :preview-src-list="srcList"
                                                @click="getPicPreviewList(item)">
                                            </el-image>
                                            <el-image style="width: 200px; height: 200px;margin:15px"
                                                :src="baseUrl + item.middlePhotoAddress" :preview-src-list="srcList"
                                                @click="getPicPreviewList(item)">
                                            </el-image>
                                            <el-image style="width: 200px; height: 200px;margin:15px"
                                                :src="baseUrl + item.rightPhotoAddress" :preview-src-list="srcList"
                                                @click="getPicPreviewList(item)">
                                            </el-image>
                                        </el-row>
                                    </div>
                                </div>
                            </div>
                            <div v-else> 该患者没有相关照片！</div>
                            <div class="pic-tabs">
                                <span class="fangda-icon" @click="openPicUploadDialog"><i
                                        class="el-icon-zoom-in"></i></span>
                                <el-tabs v-model="picActiveName" type="card" @tab-click="picTabHandleClick">

                                    <el-tab-pane label="电脑" name="computer">
                                        <el-form :model="computerPictureForm" ref="computerPictureForm" size="small"
                                            :inline="true" label-width="78px" :rules="computerPictureFormRules">
                                            <el-form-item label="照片类型" prop="photoUploadType">
                                                <el-select v-model="computerPictureForm.photoUploadType"
                                                    placeholder="请选择照片类型" style="width: 240px">
                                                    <el-option v-for="dict in dict.type.photo_upload_type" :key="dict.value"
                                                        :label="dict.label" :value="dict.value"></el-option>
                                                </el-select>
                                            </el-form-item>
                                            <el-form-item label="光照类型" prop="photoLightingType">
                                                <el-select v-model="computerPictureForm.photoLightingType"
                                                    placeholder="请选择光照类型" style="width: 240px">
                                                    <el-option v-for="dict in dict.type.photo_lighting_type"
                                                        :key="dict.value" :label="dict.label"
                                                        :value="dict.value"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-form>
                                    </el-tab-pane>
                                    <el-tab-pane label="上传" name="handUpload">
                                        <el-form :model="pictureForm" ref="pictureForm" size="small" :inline="true"
                                            label-width="78px" :rules="pictureFormRules">
                                            <el-form-item label="照片类型" prop="photoUploadType">
                                                <el-select v-model="pictureForm.photoUploadType" placeholder="请选择照片类型"
                                                    style="width: 240px">
                                                    <el-option v-for="dict in dict.type.photo_upload_type" :key="dict.value"
                                                        :label="dict.label" :value="dict.value"></el-option>
                                                </el-select>
                                            </el-form-item>
                                            <el-form-item label="光照类型" prop="photoLightingType">
                                                <el-select v-model="pictureForm.photoLightingType" placeholder="请选择光照类型"
                                                    style="width: 240px">
                                                    <el-option v-for="dict in dict.type.photo_lighting_type"
                                                        :key="dict.value" :label="dict.label"
                                                        :value="dict.value"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-form>
                                        <el-row style="display:flex;justify-content:space-around;" v-if="uploadPicShow">
                                            <div class="text-center">
                                                <leftPic :user="leftPaceForm" @getUserAvatarUrl="getPic"
                                                    :typeInfo="leftType"></leftPic>
                                                <div style="text-align:center">左脸照</div>
                                            </div>
                                            <div class="text-center">
                                                <centerPic :user="centerPaceForm" @getUserAvatarUrl="getPic"
                                                    :typeInfo="centerType"></centerPic>
                                                <div style="text-align:center">正脸照</div>
                                            </div>
                                            <div class="text-center">
                                                <rightPic :user="rightPaceForm" @getUserAvatarUrl="getPic"
                                                    :typeInfo="rightType"></rightPic>
                                                <div style="text-align:center">右脸照</div>
                                            </div>
                                        </el-row>
                                        <el-button style="margin: 20px auto;display: block;" type="primary" size="mini"
                                            @click="savePics">保 存</el-button>
                                    </el-tab-pane>
                                </el-tabs>
                            </div>
                        </el-tab-pane>
                        <el-tab-pane label="处方" name="plan">
                            <el-row>处方日期:{{ chufangCreateTime }} 处方医生:{{ chufangCreateBy }}</el-row>
                            <el-row v-for="Mitem in planListArr" :key="Mitem.index" class="plan-row">
                                <!-- <div>方案大类:{{Mitem.planCategoryName}} </div> -->
                                <div v-for="item in Mitem.sysPatientPlan" :key="item.planId">
                                    <el-row>
                                        <el-col :span="3">
                                            {{ item.medicalEquipment }}
                                        </el-col>
                                        <el-col :span="2">
                                            {{ matchDict("sys_plan_usage", item.usageId) }}
                                        </el-col>
                                        <el-col :span="2">
                                            {{ item.dosage + matchDict("sys_dosage_unit", item.dosageUnit) }}
                                        </el-col>
                                        <el-col :span="2">
                                            {{ matchDict("sys_dosage_frequency", item.frequencyId) }}
                                        </el-col>
                                        <el-col :span="2">
                                            *{{ item.num }}
                                        </el-col>
                                    </el-row>
                                </div>
                            </el-row>
                            <div style="display:flex;justify-content:center">
                                <el-button type="primary" size="mini" @click="addNewPlanClick">新增处方</el-button>
                                <el-button type="primary" size="mini" @click="updatePlanClick">修改处方</el-button>
                            </div>
                        </el-tab-pane>
                        <el-tab-pane label="治疗记录" name="treatmentRecords">
                            <el-row>
                                <el-col :span="6">
                                    <el-row
                                        style="text-align:center;line-height: 35px;border-bottom: 1px solid black;">治疗处方</el-row>
                                    <div style="line-height: 35px;border-bottom: 1px solid black;cursor:pointer"
                                        v-for="item in HISList" :key="item.index"
                                        :class="item.patientPlanId === activePatientPlanId ? 'redColor' : ''"
                                        @click="planClick(item)"> {{ item.createTime }} {{ item.medicalEquipment }}
                                        数量{{ item.num }}
                                        已治疗{{ item.treatmentNum }} 未治疗{{ item.restTreatmentNum }}
                                    </div>
                                </el-col>
                                <el-col :span="18">
                                    <el-form :model="treatmentForm" ref="treatmentForm" size="small" :inline="true"
                                        label-width="78px">
                                        <el-form-item label="治疗医生" prop="doctorId">
                                            <el-select v-model="treatmentForm.doctorId" placeholder="请选择治疗医生"
                                                style="width: 240px" clearable>
                                                <el-option v-for="item in doctorList" :key="item.userId"
                                                    :label="item.userName" :value="item.userId"></el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="治疗日期" prop="createTime">
                                            <el-date-picker v-model="treatmentForm.createTime" type="datetime"
                                                placeholder="治疗日期" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss">
                                            </el-date-picker>
                                        </el-form-item>
                                        <el-form-item label="治疗类别" prop="catgory">
                                            <el-select v-model="treatmentForm.treatKindId" placeholder="请选择治疗类别"
                                                style="width: 240px" clearable>
                                                <el-option v-for="dict in dict.type.sys_treatment_type" :key="dict.value"
                                                    :label="dict.label" :value="dict.value"></el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="治疗项目" prop="project">
                                            <el-select v-model="treatmentForm.treatItemId" placeholder="请选择治疗项目"
                                                style="width: 240px" clearable>
                                                <el-option v-for="dict in dict.type.sys_treatment_program" :key="dict.value"
                                                    :label="dict.label" :value="dict.value"></el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="治疗参数" prop="param">
                                            <el-select v-model="treatmentForm.treatParameterId" placeholder="请选择治疗参数"
                                                style="width: 240px" clearable>
                                                <el-option v-for="dict in dict.type.sys_treatment_param" :key="dict.value"
                                                    :label="dict.label" :value="dict.value"></el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="备注">
                                            <el-input v-model="treatmentForm.remark" placeholder="请输入备注" clearable
                                                style="width: 240px" />
                                        </el-form-item>
                                    </el-form>
                                    <el-button type="primary" size="mini" style="display:block;margin:0 auto"
                                        @click="addNewTreatmentRecord">
                                        保存</el-button>
                                    <div style="text-align:center;margin:15px;">治疗记录</div>
                                    <div>
                                        <el-table :data="treatmentFormList">

                                            <el-table-column label="治疗记录id" align="center" key="treatLogId"
                                                prop="treatLogId" />
                                            <el-table-column label="处方日期" align="center" key="createTime" prop="createTime"
                                                width="160">
                                            </el-table-column>

                                            <el-table-column label="处方医生" align="center" key="doctorName"
                                                prop="doctorName" />
                                            <el-table-column label="治疗类别" align="center" key="treatKindIdName"
                                                prop="treatKindIdName">
                                            </el-table-column>
                                            <el-table-column label="治疗项目" align="center" key="treatItemIdName"
                                                prop="treatItemIdName" />
                                            <el-table-column label="治疗参数" align="center" key="treatParameterIdName"
                                                prop="treatParameterIdName">
                                            </el-table-column>
                                            <!-- <el-table-column
                                                label="治疗医生"
                                                align="center"
                                                key="doctorIdName"
                                                prop="doctorIdName"
                                            />
                                            <el-table-column
                                                label="治疗日期"
                                                align="center"
                                                key="createTime"
                                                prop="createTime"
                                            >
                                            </el-table-column> -->
                                            <el-table-column label="处方数量" align="center" key="cfnumber" prop="cfnumber">
                                            </el-table-column>
                                            <el-table-column label="剩余数量" align="center" prop="cfrest">

                                            </el-table-column>
                                            <el-table-column label="备注" align="center" prop="remark">

                                            </el-table-column>
                                            <el-table-column label="操作" align="center" width="160"
                                                class-name="small-padding fixed-width">
                                                <template slot-scope="scope">
                                                    <el-button size="mini" type="text" @click="handleEdit(scope.row)"
                                                        v-hasPermi="['system:inquiry:edit']">编辑</el-button>
                                                    <el-button size="mini" type="text" @click="handleDel(scope.row)"
                                                        v-hasPermi="['system:inquiry:edit']">删除</el-button>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                        <pagination v-show="total > 0" :total="total" :page.sync="treatmentParams.pageNum"
                                            :limit.sync="treatmentParams.pageSize" @pagination="getTreatmentList" />
                                    </div>
                                </el-col>
                            </el-row>
                        </el-tab-pane>
                    </el-tabs>

                </el-col>
            </el-row>
        </el-row>
        <el-dialog :title="planTitle" width="70%" :visible.sync="isNewPlan" append-to-body>
            <plan-page v-if="isNewPlan" :addOrUpdate="addOrUpdate" :planCategoryData="planCategoryData"
                :patientId="baseInfo.patientId" :visitId="visitInfo.visitId" @reFreshPlanList="refreshPlan"
                @closePlanPage="closePlanPage"></plan-page>
        </el-dialog>
        <el-dialog title="就诊记录详情" :visible.sync="tabsOpen" width="700px" append-to-body>
            <tabs />
        </el-dialog>
        <el-dialog title="治疗记录修改" :visible.sync="treatmentDetailOpen" width="700px" append-to-body>
            <el-form :model="treatmentDetailForm" ref="treatmentDetailForm" size="small" :inline="true" label-width="78px">
                <el-form-item label="治疗医生" prop="doctorId">
                    <el-select v-model="treatmentDetailForm.doctorId" placeholder="请选择治疗医生" style="width: 240px" clearable>
                        <el-option v-for="item in doctorList" :key="item.userId" :label="item.userName"
                            :value="item.userId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="治疗日期" prop="createTime">
                    <el-date-picker v-model="treatmentDetailForm.createTime" type="datetime" placeholder="治疗日期"
                        style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="治疗类别" prop="catgory">
                    <el-select v-model="treatmentDetailForm.treatKindId" placeholder="请选择治疗类别" style="width: 240px"
                        clearable>
                        <el-option v-for="dict in dict.type.sys_treatment_type" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="治疗项目" prop="project">
                    <el-select v-model="treatmentDetailForm.treatItemId" placeholder="请选择治疗项目" style="width: 240px"
                        clearable>
                        <el-option v-for="dict in dict.type.sys_treatment_program" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="治疗参数" prop="param">
                    <el-select v-model="treatmentDetailForm.treatParameterId" placeholder="请选择治疗参数" style="width: 240px"
                        clearable>
                        <el-option v-for="dict in dict.type.sys_treatment_param" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="treatmentDetailForm.remark" placeholder="请输入备注" clearable style="width: 240px" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="treatmentDetailOpen = false">取 消</el-button>
                <el-button type="primary" @click="updateTreatmentDetail">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="照片上传" :visible.sync="picUploadDialogOpen" width="100%" append-to-body>
            <el-tabs v-model="picActiveName" type="card" @tab-click="picTabHandleClick">
                <el-tab-pane label="电脑" name="computer">
                    <el-form :model="computerPictureForm" ref="computerPictureForm" size="small" :inline="true"
                        label-width="78px" :rules="computerPictureFormRules">
                        <el-form-item label="照片类型" prop="photoUploadType">
                            <el-select v-model="computerPictureForm.photoUploadType" placeholder="请选择照片类型"
                                style="width: 240px">
                                <el-option v-for="dict in dict.type.photo_upload_type" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="光照类型" prop="photoLightingType">
                            <el-select v-model="computerPictureForm.photoLightingType" placeholder="请选择光照类型"
                                style="width: 240px">
                                <el-option v-for="dict in dict.type.photo_lighting_type" :key="dict.value"
                                    :label="dict.label" :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="上传" name="handUpload">
                    <el-form :model="pictureForm" ref="pictureForm" size="small" :inline="true" label-width="78px"
                        :rules="pictureFormRules">
                        <el-form-item label="照片类型" prop="photoUploadType">
                            <el-select v-model="pictureForm.photoUploadType" placeholder="请选择照片类型" style="width: 240px">
                                <el-option v-for="dict in dict.type.photo_upload_type" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="光照类型" prop="photoLightingType">
                            <el-select v-model="pictureForm.photoLightingType" placeholder="请选择光照类型" style="width: 240px">
                                <el-option v-for="dict in dict.type.photo_lighting_type" :key="dict.value"
                                    :label="dict.label" :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <el-row style="display:flex;justify-content:space-around;" v-if="uploadPicShow">
                        <div class="text-center">
                            <leftPic :user="leftPaceForm" @getUserAvatarUrl="getPic" :typeInfo="leftType"></leftPic>
                            <div style="text-align:center">左脸照</div>
                        </div>
                        <div class="text-center">
                            <centerPic :user="centerPaceForm" @getUserAvatarUrl="getPic" :typeInfo="centerType"></centerPic>
                            <div style="text-align:center">正脸照</div>
                        </div>
                        <div class="text-center">
                            <rightPic :user="rightPaceForm" @getUserAvatarUrl="getPic" :typeInfo="rightType"></rightPic>
                            <div style="text-align:center">右脸照</div>
                        </div>
                    </el-row>
                    <el-button style="margin: 20px auto;display: block;" type="primary" size="mini" @click="savePics">保
                        存</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
    </div>
</template>

<script>
import { listUser, deptTreeSelect } from "@/api/system/user";
import { listClassify } from "@/api/system/classify";
import {
    addressJson,
    findPatient,
    addVisit,
    delVisit,
    addPhoto,
    batchAddPatientPlan,
    delPic,
    listPlanByCategoryId,
    listPlanByVisitId,
    addTreatmentRecord,
    updateTreatmentRecord,
    listLog,
    delTreat,
    listPatientPlan,
} from "@/api/patients/personal";
import { listPhotos } from "@/api/patients/patient";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";
import tabs from "@/views/patients/personal/tabs";
import leftPic from "./uploadPic.vue";
import centerPic from "./uploadPic.vue";
import rightPic from "./uploadPic.vue";
import PlanPage from "../patient/plan.vue";
export default {
    name: "personal",
    components: {
        Treeselect,
        tabs,
        leftPic,
        centerPic,
        rightPic,
        PlanPage,
    },
    dicts: [
        "sys_user_sex",
        "sys_manage_diseases",
        "sys_diagnosis_status",
        "photo_upload_type",
        "photo_lighting_type",
        "sys_plan_category",
        "sys_dosage_unit",
        "sys_dosage_frequency",
        "sys_plan_usage",
        "sys_treatment_type",
        "sys_treatment_program",
        "sys_treatment_param",
        "sys_user_category",
    ],
    data() {
        //验证手机号的规则;
        var checkMobile = (rule, value, cb) => {
            // 验证手机号的正则表达式
            const regMobile =
                /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
            if (regMobile.test(value)) {
                return cb();
            }
            cb(new Error("请输入合法的手机号"));
        };
        return {
            baseUrl: process.env.VUE_APP_BASE_API,
            activeName: "medicalRecords",
            picActiveName: "handUpload",
            // 省市区
            areaList: [],
            // 查询参数
            queryParams: {
                patientPhone: undefined,
            },
            queryFormRules: {
                patientPhone: [
                    {
                        required: true,
                        message: "患者手机号不能为空",
                        trigger: "blur",
                    },
                    {
                        validator: checkMobile,
                        message: "请输入正确的手机号码",
                        trigger: "blur",
                    },
                ],
            },
            baseInfo: {
                patientId: undefined,
                cardNumber: undefined,
                patientName: undefined,
                sex: undefined,
                birthDate: undefined,
                patientPhone: undefined,
                area: undefined,
                address: undefined,
                category: undefined,
            },
            baseInfoFormRules: {
                patientName: [
                    {
                        required: true,
                        message: "患者姓名不能为空",
                        trigger: "blur",
                    },
                ],
                sex: [
                    {
                        required: true,
                        message: "患者性别不能为空",
                        trigger: "blur",
                    },
                ],
                patientPhone: [
                    {
                        required: true,
                        message: "患者手机号不能为空",
                        trigger: "blur",
                    },
                    {
                        validator: checkMobile,
                        message: "请输入正确的手机号码",
                        trigger: "blur",
                    },
                ],
                // area: [
                //     {
                //         required: true,
                //         message: "患者地址不能为空",
                //         trigger: "blur",
                //     },
                // ],
            },

            visitInfo: {
                createTime: undefined,
                deptId: undefined,
                visitId: undefined,
                diseaseId: undefined,
                diseaseClassifyId: undefined,
                doctorId: undefined,
                status: undefined,
                visitStatus: undefined,
                parentId: null,
            },
            // 科室树选项
            deptOptions: undefined,
            deptOptionsChildren: [],
            visitInfoFormRules: {
                createTime: [
                    {
                        required: true,
                        message: "就诊日期不能为空",
                        trigger: "blur",
                    },
                ],
                deptId: [
                    {
                        required: true,
                        message: "科室不能为空",
                        trigger: "blur",
                    },
                ],
                diseaseId: [
                    {
                        required: true,
                        message: "专病名称不能为空",
                        trigger: "blur",
                    },
                ],
                diseaseClassifyId: [
                    {
                        required: true,
                        message: "专病分类不能为空",
                        trigger: "blur",
                    },
                ],
                doctorId: [
                    {
                        required: true,
                        message: "专属医生不能为空",
                        trigger: "blur",
                    },
                ],
                status: [
                    {
                        required: true,
                        message: "诊断状态不能为空",
                        trigger: "blur",
                    },
                ],
            },
            //专病分类
            classifyList: [
                { diseaseClassifyId: null, diseaseClassifyName: null },
            ],
            doctorList: [],
            visitStatusList: [
                { id: 1, name: "初诊" },
                { id: 2, name: "复诊" },
            ],

            picData: {},
            picDataQueryParams: { diseaseId: null },
            srcList: [],
            medicalRecordsList: [],
            tabsOpen: false,
            isRequest: true,
            loading: false,
            finishStatus: false,
            activeVisitId: null,
            activePatientPlanId: null,
            treatmentForm: {},
            treatmentFormList: [],
            treatmentParams: { pageNum: 1, pageSize: 10 },
            total: 0,
            computerPictureForm: {},
            computerPictureFormRules: {},
            pictureForm: {
                photoLightingType: "",
                photoUploadType: "",
                leftPhotoAddress: null,
                middlePhotoAddress: null,
                rightPhotoAddress: null,
            },
            pictureFormRules: {
                photoUploadType: [
                    {
                        required: true,
                        message: "照片类型不能为空",
                        trigger: "blur",
                    },
                ],
                photoLightingType: [
                    {
                        required: true,
                        message: "光照类型不能为空",
                        trigger: "blur",
                    },
                ],
            },
            leftPaceForm: { avatar: "" },
            leftType: "left",
            centerType: "center",
            rightType: "right",
            uploadPicShow: true,
            centerPaceForm: { avatar: "" },
            rightPaceForm: { avatar: "" },
            isNewPlan: false,
            addOrUpdate: null,
            planCategoryData: [],
            planTitle: "",
            planListArr: [],
            chufangCreateTime: "",
            chufangCreateBy: "",
            HISList: [],
            treatmentDetailOpen: false,
            treatmentDetailForm: {},
            picUploadDialogOpen: false,
        };
    },
    watch: {},
    created() {
        this.getAddressData();
        this.getDoctorData();
        this.getDeptTree();
    },
    computed: {},
    methods: {
        openPicUploadDialog() {
            this.picUploadDialogOpen = true;
        },
        morePics() { },
        getPic(data) {
            if (data.type === "left") {
                this.pictureForm.leftPhotoAddress = data.imgUrl;
            }
            if (data.type === "center") {
                this.pictureForm.middlePhotoAddress = data.imgUrl;
            }
            if (data.type === "right") {
                this.pictureForm.rightPhotoAddress = data.imgUrl;
            }
        },

        picTabHandleClick() { },
        /**tab-click */
        tabHandleClick(tab) {
            if (tab.name === "pic") {
                this.getPhotoList();
            }
            if (tab.name === "plan") {
                this.getPlanListByVisitId();
            }
            if (tab.name === "treatmentRecords") {
                this.getHIS();
            }
        },
        getPhotoList() {
            listPhotos({
                patientId: this.baseInfo.patientId,
            }).then((res) => {
                if (res.rows.length > 0) {
                    this.picData = res.rows;
                    this.picData.forEach((item) => {
                        item.photoLightingTypeName = this.matchDict(
                            "photo_lighting_type",
                            item.photoLightingType
                        );
                        item.photoUploadTypeName = this.matchDict(
                            "photo_upload_type",
                            item.photoUploadType
                        );
                    });
                } else {
                    this.picData = [];
                }
            });
        },
        getPhotoListByVisitId() {
            listPhotos({ visitId: this.visitInfo.visitId }).then(
                (res) => {
                    if (res.rows.length > 0) {
                        this.picData = res.rows;
                    } else {
                        this.picData = [];
                    }
                }
            );
        },

        /** 查询科室下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then((response) => {
                this.deptOptions = response.data;
                this.deptOptionsChildren = response.data[0].children;
                if (this.deptOptionsChildren.length == 1) {
                    this.visitInfo.deptId = this.deptOptionsChildren[0].id;
                }
            });
        },
        updateTreatmentDetail() {
            updateTreatmentRecord(this.treatmentDetailForm).then((res) => {
                this.getTreatmentList();
                this.treatmentDetailOpen = false;
                this.$message.success("修改成功");
            });
        },
        handleEdit(row) {
            this.treatmentDetailOpen = true;
            this.treatmentDetailForm = row;
        },
        handleDel(row) {
            this.$modal
                .confirm(
                    '是否确认删除治疗记录id为"' + row.treatLogId + '"的数据项？'
                )
                .then(function () {
                    return delTreat(row.treatLogId);
                })
                .then(() => {
                    this.getTreatmentList();
                    this.$message.success("删除成功");
                })
                .catch(() => { });
        },
        addNewTreatmentRecord() {
            if (this.activePatientPlanId) {
                this.treatmentForm.patientPlanId = this.activePatientPlanId;
                addTreatmentRecord(this.treatmentForm).then((res) => {
                    this.getTreatmentList();
                    this.$message.success("保存成功");
                });
            }
        },
        getHIS() {
            if (this.baseInfo.patientId) {
                const mData = {
                    patientId: this.baseInfo.patientId,
                    planCategoryId: "2",
                };
                listPatientPlan(mData).then((res) => {
                    res.rows.forEach((item) => {
                        item.dosageUnitName = this.matchDict(
                            "sys_dosage_unit",
                            item.dosageUnit
                        );
                        item.frequencyIdName = this.matchDict(
                            "sys_dosage_frequency",
                            item.frequencyId
                        );
                    });
                    this.HISList = res.rows;
                });
            } else {
                this.$message.info("没有病人id");
            }
        },
        planClick(data) {
            this.activePatientPlanId = data.patientPlanId;
            this.getTreatmentList();
        },

        getTreatmentList() {
            this.treatmentParams.patientPlanId = this.activePatientPlanId;
            listLog(this.treatmentParams).then((res) => {
                console.log(res);
                res.rows.forEach((item) => {
                    item.doctorName = this.matchDoctor(item.doctorId);
                    item.treatItemIdName = this.matchDict(
                        "sys_treatment_program",
                        item.treatItemId
                    );
                    item.treatKindIdName = this.matchDict(
                        "sys_treatment_type",
                        item.treatKindId
                    );
                    item.treatParameterIdName = this.matchDict(
                        "sys_treatment_param",
                        item.treatParameterId
                    );
                });
                this.treatmentFormList = res.rows;
                this.total = res.total;
            });
        },
        async visitsClick(data) {
            this.activeName = "medicalRecords";
            this.activeVisitId = data.visitId;
            await listClassify({
                pageNum: 1,
                pageSize: 1000,
                diseaseId: Number(data.diseaseId),
            }).then((response) => {
                this.classifyList = response.rows;
            });
            Object.keys(this.visitInfo).forEach((item) => {
                this.visitInfo[item] = data[item];
            });
        },
        //就诊记录修改
        updateBaseInfo() {
            if (this.visitInfo.visitId) {
                this.$refs["visitInfoForm"].validate((valid) => {
                    if (valid) {
                        let mData = {
                            patientId: this.baseInfo.patientId,
                            visitId: null,
                        };
                        Object.keys(this.visitInfo).forEach((key) => {
                            mData[key] = this.visitInfo[key];
                        });
                        addVisit(mData).then((res) => {
                            this.loading = true;
                            this.activeVisitId = this.visitInfo.visitId;
                            this.loading = false;
                            this.queryParams.patientPhone =
                                this.baseInfo.patientPhone;
                            this.handleQuery();
                            this.$message.success("新增就诊信息成功");
                        });
                    }
                });
            } else {
                this.$message.warning("请点击要修改的就诊");
            }
        },
        //就诊记录保存
        saveBaseInfo() {
            if (this.baseInfo.patientId) {
                this.$refs["visitInfoForm"].validate((valid) => {
                    if (valid) {
                        let mData = {
                            patientId: this.baseInfo.patientId,
                            visitId: null,
                        };
                        Object.keys(this.visitInfo).forEach((key) => {
                            mData[key] = this.visitInfo[key];
                        });
                        mData.visitId = null; //新增修改接口是一个  有visitId就是修改 没有就是新增
                        addVisit(mData).then((res) => {
                            this.loading = true;
                            this.visitInfo.visitId = res.data.visitId;
                            this.activeVisitId = res.data.visitId;
                            this.loading = false;
                            this.queryParams.patientPhone =
                                this.baseInfo.patientPhone;
                            this.handleQuery();
                            this.$message.success("新增就诊信息成功");
                        });
                    }
                });
            } else {
                this.$refs["baseInfoForm"].validate((valid) => {
                    if (valid) {
                        this.$refs["visitInfoForm"].validate((valid) => {
                            if (valid) {
                                if (!!this.baseInfo.area) {
                                    this.baseInfo.provinceId =
                                        this.baseInfo.area[0];
                                    this.baseInfo.cityId =
                                        this.baseInfo.area[1];
                                    this.baseInfo.countyId =
                                        this.baseInfo.area[2];
                                }
                                let mData = {
                                    patientId: null,
                                    visitId: null,
                                    sysPatient: this.baseInfo,
                                };
                                Object.keys(this.visitInfo).forEach((key) => {
                                    mData[key] = this.visitInfo[key];
                                });
                                addVisit(mData).then((res) => {
                                    this.loading = true;
                                    this.baseInfo.patientId =
                                        res.data.patientId;
                                    this.visitInfo.visitId = res.data.visitId;
                                    this.loading = false;
                                    this.queryParams.patientPhone =
                                        this.baseInfo.patientPhone;
                                    this.handleQuery();
                                    this.$message.success("新增就诊信息成功");
                                });
                            }
                        });
                    }
                });
            }
        },
        deletePics(photoId) {
            delPic(photoId).then((res) => {
                this.getPhotoList();
                this.$message.success("删除成功");
            });
        },
        savePics() {
            this.$refs["pictureForm"].validate((valid) => {
                if (valid) {
                    this.uploadPicShow = false;
                    this.pictureForm.patientId = this.baseInfo.patientId;
                    addPhoto(this.pictureForm).then((res) => {
                        this.uploadPicShow = true;
                        this.getPhotoList();
                        this.$message.success("保存成功");
                    });
                }
            });
        },
        //保存处方
        savePlan() {
            if (
                this.oralDrugCheckList.length > 0 ||
                this.externalUsedDrugCheckList.length > 0
            ) {
                let planArr = [];
                this.oralDrugCheckList.forEach((item) => {
                    this.planCategoryData.oralDrug.forEach((it) => {
                        it.patientId = this.baseInfo.patientId;
                        it.visitId = this.visitInfo.visitId;
                        if (item == it.planId) {
                            planArr.push(it);
                        }
                    });
                });
                this.externalUsedDrugCheckList.forEach((item) => {
                    this.planCategoryData.externalUsedDrug.forEach((it) => {
                        it.patientId = this.baseInfo.patientId;
                        it.visitId = this.visitInfo.visitId;
                        if (item == it.planId) {
                            planArr.push(it);
                        }
                    });
                });
                planArr.forEach((itSelf) => {
                    delete itSelf.planId;
                    delete itSelf.createTime;
                    delete itSelf.updateTime;
                    delete itSelf.createBy;
                });
                batchAddPatientPlan(planArr).then((res) => {
                    this.step = 0;
                    this.resetAllData();
                    this.$message.success("就诊录入已完成");
                });
            } else {
                this.$message.warning("请至少选择一项方案");
            }
        },

        resetAllData() {
            this.$refs["baseInfoForm"].resetFields();
            this.$refs["visitInfoForm"].resetFields();
            this.medicalRecordsList = [];
        },
        detail(data) {
            this.tabsOpen = true;
        },
        deleteDetail(data) {
            delVisit(data.visitId).then((res) => {
                this.handleQuery();
                this.$message.success("删除成功");
            });
        },
        cancel() { },

        handleClick(tab, event) {
            console.log(tab, event);
        },
        getPicPreviewList(it) {
            this.srcList = [
                this.baseUrl + it.leftPhotoAddress,
                this.baseUrl + it.middlePhotoAddress,
                this.baseUrl + it.rightPhotoAddress,
            ];
        },
        getDoctorData() {
            listUser({ pageNum: 1, pageSize: 1000, roleId: 101 }).then(
                (res) => {
                    this.doctorList = res.rows;
                }
            );
        },
        getAddressData() {
            addressJson().then((res) => {
                this.areaList = res.data;
            });
        },

        handleQuery() {
            this.$refs["queryForm"].validate((valid) => {
                if (valid) {
                    findPatient(this.queryParams).then((res) => {
                        let resultPatient = res.data.patient;
                        if (resultPatient) {
                            Object.keys(this.baseInfo).forEach((key) => {
                                this.baseInfo[key] = resultPatient[key];
                            });
                            this.baseInfo.area = [
                                Number(resultPatient.provinceId),
                                Number(resultPatient.cityId),
                                Number(resultPatient.countyId),
                            ];
                        } else {
                            Object.keys(this.baseInfo).forEach((key) => {
                                this.baseInfo[key] = null;
                            });
                            this.baseInfo.area = [null, null, null];
                            Object.keys(this.visitInfo).forEach((key) => {
                                this.visitInfo[key] = null;
                            });
                        }
                        let result = res.data.visits;
                        result.forEach((item) => {
                            item.visitStatus = 1;
                            item.name =
                                item.createTime +
                                this.getParentIdValue(item.parentId) +
                                this.matchDict(
                                    "sys_manage_diseases",
                                    item.diseaseId
                                ) +
                                "-" +
                                item.diseaseClassifyName +
                                "-" +
                                this.matchDoctor(item.doctorId);
                        });
                        this.medicalRecordsList = result;
                    });
                }
            });
        },
        refresh() {
            location.reload();
        },
        getListClassify(value) {
            const findResult = this.medicalRecordsList.find((item) => {
                return item.diseaseId === value;
            });
            if (findResult) {
                this.visitInfo.visitStatus = 2;
                this.visitInfo.parentId = findResult.parentId;
            } else {
                this.visitInfo.visitStatus = 1;
                this.visitInfo.parentId = null;
            }

            listClassify({
                pageNum: 1,
                pageSize: 1000,
                diseaseId: Number(value),
            }).then((response) => {
                this.classifyList = response.rows;
            });
        },
        getParentIdValue(parentId) {
            return parentId ? "(复诊)" : "(初诊)";
        },
        /** id转化成对应的文字 */
        matchDict: function (key, id) {
            let _this = this;
            const result = _this.dict.type[key];
            let textValue = "";
            result.forEach((item) => {
                if (item.raw.dictValue == id) {
                    textValue = item.raw.dictLabel;
                }
            });
            return textValue;
        },
        /** doctorId转化成对应的医生名字 */
        matchDoctor(doctorId) {
            return this.doctorList.find((item) => {
                return item.userId === doctorId;
            }).userName;
        },
        /** 用户管理头像修改返回的地址更新到form */
        updateLeftAvatarInfo(avatarUrl) { },
        updateCenterAvatarInfo(avatarUrl) { },
        updateRightAvatarInfo(avatarUrl) { },
        refreshPlan() {
            this.getPlanListByVisitId();
            this.isNewPlan = false;
        },
        closePlanPage() {
            this.isNewPlan = false;
        },
        addNewPlanClick() {
            if (this.visitInfo.diseaseId) {
                this.planCategoryData = [];
                listPlanByCategoryId({
                    diseaseId: this.visitInfo.diseaseId,
                }).then((res) => {
                    this.addOrUpdate = 1;
                    res.data.forEach((item) => {
                        if (item.sysPlans.length > 0) {
                            this.planCategoryData.push(item);
                        }
                    });
                    this.planTitle = "新增方案";
                    this.isNewPlan = true;
                });
            } else {
                this.$message.warning(
                    "没有专病名称,无法获得该专病名称下的方案列表"
                );
            }
        },
        updatePlanClick() {
            this.addOrUpdate = 2;
            this.planCategoryData = [];
            this.planListArr.forEach((item) => {
                item.sysPlans = item.sysPatientPlan;
            });
            this.planCategoryData = this.planListArr;
            this.planTitle = "修改方案";
            this.isNewPlan = true;
        },
        getPlanListByVisitId() {
            this.planListArr = [];
            listPlanByVisitId({ visitId: this.visitInfo.visitId }).then(
                (res) => {
                    res.data.forEach((item) => {
                        if (item.sysPatientPlan.length > 0) {
                            this.planListArr.push(item);
                        }
                    });
                    let mData = this.planListArr[0];
                    this.chufangCreateTime = mData.sysPatientPlan[0].createTime;
                    this.chufangCreateBy = mData.sysPatientPlan[0].createBy;
                }
            );
        },
    },
};
</script>

<style scoped>
.medical-records {
    padding: 5px;
    cursor: pointer;
    border-bottom: 1px solid #000;
}

.medical-records:hover {
    background-color: #1890ff;
}

.redColor {
    color: red;
}

.plan-row {
    margin: 15px 0;
    line-height: 28px;
}

.el-checkbox-group {
    font-size: 14px;
}

.avatar-uploader .el-upload {
    border: 1px dashed black;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.pic-tabs {
    position: relative;
}

.fangda-icon {
    position: absolute;
    top: 15px;
    right: 20px;
    z-index: 1;
    cursor: pointer;
    font-size: 20px;
}
</style>